package com.sqx.modules.packageTime.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.modules.cityInfo.entity.CityInfo;
import com.sqx.modules.cityInfo.service.CityInfoService;
import com.sqx.modules.packageTime.entity.PackageTime;
import com.sqx.modules.packageTime.dao.PackageTimeDao;
import com.sqx.modules.packageTime.service.PackageTimeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.sqx.common.utils.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.time.LocalDateTime;

/**
 * 包时价格 服务实现类
 * @author wuChang
 * @since 2024-05-07
 */
@Service
public class PackageTimeServiceImp extends ServiceImpl<PackageTimeDao, PackageTime> implements PackageTimeService {
    @Autowired
    private CityInfoService cityInfoService;

    @Override
    public Result savePackageTime(PackageTime packageTime) {
        if (packageTime.getCityId() != null) {
            CityInfo cityInfo = cityInfoService.getById(packageTime.getCityId());
            packageTime.setCityName(cityInfo.getCityName());
        }
        if (packageTime.getTimeId() != null) {
            return Result.upStatus(baseMapper.updateById(packageTime));
        } else {
            packageTime.setCreateTime(LocalDateTime.now());
            return Result.upStatus(baseMapper.insert(packageTime));
        }
    }

    @Override
    public IPage<PackageTime> getPackageTimeList(Integer page, Integer limit, PackageTime packageTime) {
        Page<PackageTime> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<PackageTime> selectedPage = baseMapper.selectPage(pages, new QueryWrapper<>(packageTime).orderByAsc("sort"));
        if (selectedPage.getRecords().isEmpty()) {
            selectedPage = baseMapper.selectPage(pages, new QueryWrapper<PackageTime>().isNull("city_id").orderByAsc("sort"));
        }
        return selectedPage;
    }

    @Override
    public IPage<PackageTime> getAdminPackageTimeList(Integer page, Integer limit, PackageTime packageTime) {
        Page<PackageTime> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.selectPage(pages, new QueryWrapper<>(packageTime).orderByAsc("sort"));
    }
}
